
package decoderstage
import chisel3._
import chisel3.util._
import executestage.E_D_Bus
import instrfetch.I_D_Bus
import memandwritebackstage.M_D_Bus
import writebackstage.W_D_Bus

class DecoderStage extends Module{
  val io = IO(new Bundle{
    val I_Bus = Flipped(new I_D_Bus)
    val E_Bus = Flipped(new E_D_Bus)
    val M_Bus = Flipped(new M_D_Bus)
  })
  val decoder = new Decoder
  val npc = new NPC
  val grf = new GRF
  val extender = new Extender//各个模块

  val I_Bus = io.I_Bus
  val E_Bus = io.E_Bus
  val M_Bus = io.M_Bus

  val MF_Rs = Wire(UInt(32.W))
  val MF_Rt = Wire(UInt(32.W))
  decoder.io.mipsInstr := I_Bus.I_Instr
  decoder.io.D_stallInfo := E_Bus.D_stallInfo
  decoder.io.E_stallInfo := E_Bus.E_stallInfo

  npc.io.PC := I_Bus.I_PC_Pass
  npc.io.rsData := MF_Rs
  npc.io.rtData := MF_Rt
  npc.io.imm16 := decoder.io.imm16
  npc.io.imm26 := decoder.io.imm26
  npc.io.NPC_OpCode := decoder.io.NPC_OpCode

  grf.io.grfReadBus := decoder.io.grfReadBus
  grf.io.grfWriteBus := M_Bus.M_stallInfo.grfWriteBus

  extender.io.imm16 := decoder.io.imm16
  extender.io.opCode := decoder.io.EXT_OpCode

  val rs = decoder.io.grfReadBus.rs
  val rt = decoder.io.grfReadBus.rt
  val E_RegID = E_Bus.E_stallInfo.grfWriteBus.writeID
  val E_RegWE = E_Bus.E_stallInfo.grfWriteBus.writeEnable
  val E_Data = E_Bus.E_stallInfo.grfWriteBus.writeData
  MF_Rs := Mux(rs =/= 0.U && E_RegWE && E_RegID === rs,E_Data,grf.io.grfDataBus.rsData)
  MF_Rt := Mux(rt =/= 0.U && E_RegWE && E_RegID === rt,E_Data,grf.io.grfDataBus.rtData)



}
